<?php
declare(strict_types=1);

namespace App\Service;

use App\Task\ExportTask;
use App\Utils\CustomUtils;
use Hyperf\Di\Annotation\Inject;
use App\Model\Dao\SysExportLogDao;
use App\Exception\XZXValidationException;
use App\Constants\XZXResponseCode;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Task\Task;
use Hyperf\Task\TaskExecutor;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Utils\Coroutine;
use App\Utils\DateUtils;


class SysExportLogService
{
    /**
     * @Inject()
     * @var SysExportLogDao
     */
    private $SysExportLogDao;

    /**
     * @Inject()
     * @var OfficeService
     */
    private $OfficeService;

    /**
     * @param $param
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \Throwable
     * @throws \TypeError
     */
    public function addToTask($param) {
        $container = ApplicationContext::getContainer();
        $exec = $container->get(TaskExecutor::class);
        $exec->execute(new Task([ExportTask::class, 'handle'], [
            $param
        ]));
    }

    public function get($param)
    {
        $result = $this->SysExportLogDao->get($param['id']);
        if (!$result) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }
        $data = [
            'id'        => $result['id'],
            'fileName'  => $result['fileName'],
            'status'    => $result['status'],
            'remark'    => $result['remark']
        ];
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE),$data);
    }

    public function export($param, ResponseInterface $response)
    {
        $result = $this->SysExportLogDao->get($param['id']);
        if (!$result) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }
        if ($result['status'] != 1 || $result['createBy'] != $param['createBy']) {
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::DATA_NOT_FOUND));
        }

        return $response->download(strval($result['filePath']), strval($result['fileName']));
    }

    public function add($param)
    {
        $data = [
            'id'            => CustomUtils::createUUID(),
            'type'          => $param['type'],
            'createBy'      => $param['createBy'],
            'createTime'    => time(),
        ];
        
        try {
            $this->SysExportLogDao->insert($data);
        } catch (\Throwable $th) {
            CustomUtils::xzxDebug($th->getMessage());
            throw new XZXValidationException(XZXResponseCode::getMessage(XZXResponseCode::ADD_FAIL));
        }
        return CustomUtils::xeServiceReturnData(XZXResponseCode::SUCCESS_CODE,XZXResponseCode::getMessage(XZXResponseCode::SUCCESS_CODE), $data['id']);
    }

}